﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataSource;
using Exchange;
using Strategy.Linkage;
using Trader;

namespace TimePulse
{
    public class TimePulse
    {
        string date;
        SimulateMarket sm;
        StockExchange se;
        Linkage lk;
        TradeManager tm;
        string sectorType;
        string resDir;


        public TimePulse(string date)
        {
            sectorType = "Wind_SW2";
            SectorHelp.SetSectorType(sectorType);
            SimulateMarket.ClearInstance(); //清空上次运行的实例
            sm = SimulateMarket.GetInstance(date);
            se = new StockExchange(date);
            lk = new Linkage(date);
            tm = new TradeManager();
            int year = int.Parse(date.Substring(0, 4));
            int month = int.Parse(date.Substring(4, 2));
            int day = int.Parse(date.Substring(6, 2));
            DateTime st = new DateTime(year, month, day, 9, 40, 0);
            DateTime et = new DateTime(year, month, day, 14, 50, 0);
            lk.SetObserveTime(st, et, 3);
            lk.Subscrible();
            lk.OnEntrySignalEvent += new Linkage.SignalEventHandler(tm.Buy);
            lk.OnExitSignalEvent += new Linkage.SignalEventHandler(tm.Sell);
            sm.OnLevel2ReceiveEvent += new SimulateMarket.Level2ReceiveEventHandler(lk.OnLevel2Received);//添加响应
            tm.OnOrderSendEvent += new TradeManager.OrderSendEventHandler(se.OnOrderReceive);
            se.OnDealReceivedEvent += new StockExchange.DealSendEventHandler(tm.OnDealReceived);
            resDir = String.Format(@"P:\T0\CoMov\Res\{0}\{1}\{2}", sectorType, StrategyPara.get_follow_pair_arg_str(), StrategyPara.get_backtest_arg_str());
        }


        public void Run()
        {   
            List<DateTime> timeMarketList = sm.GetTimeList();
            List<DateTime> timeObserveList = lk.GetTimeSlice();
            List<DateTime> timeList = timeMarketList.Union(timeObserveList).ToList().OrderBy(x => x).ToList();
            foreach (var dt in timeList) //按时间片循环,注意顺序
            {
                Console.WriteLine(dt.ToString("HH:mm:ss fff"));
                if (dt.Second == 00 && dt.Minute ==23 && dt.Hour == 13)
                {
                    ;
                }
                //se.OnTimePulse(dt); //交易所响应 
                tm.OnTimePulse(dt); //发单系统响应
                lk.OnTimePulse(dt); //策略响应，做该时刻策略要做的事
                se.OnTimePulse(dt); // 按道理要放在首位的，为了模拟发单马上以对手价成交，不得已挪到最后
                sm.OnTimePulse(dt); //行情响应,做该时刻行情要做的事
                if (dt>=new DateTime(2017, 12, 22, 10,30, 39))
                {
                    //Console.WriteLine("stop");
                }
            }
            tm.Save(resDir);
            //lk.Save(resDir);

        }
    }
}
